#!/usr/bin/env python
# encoding: utf-8
#
# PyGadu - Pythonic Gadu-Gadu implementation
# Copyright (c) 2005,2006 Zygmunt Krynicki
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

import socket
import urllib2

class ServerDiscoveryProtocol:
    HOST = 'appmsg.gadu-gadu.pl'
    PORT = 80
    MESSAGE_FORMAT_TEXT, MESSAGE_FORMAT_HTML = range(2)
    DEFAULT_MESSAGE_FORMAT = MESSAGE_FORMAT_HTML
    DEFAULT_USER_AGENT = 'Mozilla/4.0 (compatible; MSIE 5.0; Windows 98)'
    DEFAULT_VERSION = (5,0,5,107)

    def __init__(self, number, last_message, message_format = None, version = None, user_agent = None, use_ssl = False):
        self.number = number
        self.last_message = last_message
        self.message_format = message_format or self.DEFAULT_MESSAGE_FORMAT
        self.version = version or self.DEFAULT_VERSION
        self.user_agent = user_agent or self.DEFAULT_USER_AGENT
        self.use_ssl = use_ssl
    
    def _getVersionString(self):
        return ",+".join([str(part) for part in self.version])

    def _getURL(self):
        if self.use_ssl:
            base = "/appsvc/appmsg3.asp"
        else:
            base = "/appsvc/appmsg4.asp"
        query_bits = ([
                "fmnumber=%d" % self.number,
                "version=%s" % self._getVersionString(),
                "lastmsg=%d" % self.last_message])
        if self.message_format == self.MESSAGE_FORMAT_HTML:
            query_bits.append("fmt=2")
        return "%s?%s" % (base, "&".join(query_bits))

    def _getHelloMessage(self):
        return [("Host", "appmsg.gadu-gadu.pl"),
                ("Accept", "image/gif, image/jpeg, image/pjpeg"),
                ("Accept-Language", "pl"),
                ("User-Agent", self.user_agent),
                ("Pragma", "no-cache")]

    def _parseServerInformationField(self, field):
        if field == "notoperating":
            return None
        elif ":" in field:
            host, port = field.split(":")
            return (host, int(port))
        else:
            return (field, 443)

    def _parseServerMessage(self, message):
        lines = message.replace("\r\n", "\n").split("\n")
        fields = lines[0].split(' ')
        sys_message = int(fields[0])
        server1 = self._parseServerInformationField(fields[2])
        server2 = self._parseServerInformationField(fields[3])
        return (sys_message, server1, server2, lines[3:])

    def _queryServer(self):
        opener = urllib2.build_opener()
        opener.addheaders = self._getHelloMessage()
        s = opener.open("http://%s%s" % (self.HOST, self._getURL()))
        data = s.read(1024)
        s.close()
        return data

    def talk(self):
        return self._parseServerMessage(self._queryServer())


if __name__ == "__main__":
    import sys
    import os.path
    if len(sys.argv) != 2:
        print "Usage: %s <number>" % os.path.basename(sys.argv[0])
        sys.exit()
    number = int(sys.argv[1])
    sdp = ServerDiscoveryProtocol(number, last_message=0)
    response = sdp.talk()
    if response:
        sys_message, server1, server2, message = response
        print "System message: %s" % sys_message
        if server1:
            print "Server 1:       %s:%d" % server1
        else:
            print "Server 1:       offline"
        if server2:
            print "Server 2:       %s:%d" % server2
        else:
            print "Server 2:       offline"
        print "System message"
        print "-" * 100
        for line in message:
            print line
        print "-" * 100
    else:
        print "Nothing to say..."
